﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using Jayden.Dll.Core;
using Jayden.Dll.Core.Persistence;
using Jayden.Dll.Core.Persistence.Data;
using Jayden.Dll.Core.Persistence.Data.SQLite;
using Jayden.Dll.Core.Persistence.Models;

namespace Jayden.Dll.Series.Providers
{
	public class SQLiteEpisodeInfoDataAccess : SQLiteDataAccess<EpisodeInfo>
	{
		public SQLiteEpisodeInfoDataAccess(Configuration config, UnitOfWork uow, Entity entity) : base(config, uow, entity) { }

		public IEnumerable<EpisodeInfo> FindByShowInfoId(string id)
		{
			string commandText = Helper.GenerateSelect(Entity, Entity["ShowInfoId"]);
			using (DbCommandProxy command = CreateCommand(commandText))
			{
				CreateParameter(command, "ShowInfoId", id);
				DbDataReader reader = command.Command.ExecuteReader();
				return EnumerateFromReader(reader);
			}
		}

		public IEnumerable<EpisodeInfo> FindByAirDate(DateTime? startDate, DateTime? endDate, string[] showIds)
		{
			List<string> parts = new List<string>();
			if (startDate.HasValue)
				parts.Add("AirDate >= @StartDate");
			if (endDate.HasValue)
				parts.Add("AirDate <= @EndDate");
			if (showIds != null && showIds.Length > 0)
				parts.Add(string.Format("ShowInfoId IN(\"{0}\")", string.Join("\",\"", showIds)));
			string commandText = Helper.GenerateSelect(null, Entity.Table.TableName, string.Join(" AND ", parts), null, new string[] { "AirDate", "PkId" }, null, null);
			using (DbCommandProxy command = CreateCommand(commandText))
			{
				if (startDate.HasValue)
					CreateParameter(command, "StartDate", startDate.Value);
				if (endDate.HasValue)
					CreateParameter(command, "EndDate", endDate.Value);
				DbDataReader reader = command.Command.ExecuteReader();
				return EnumerateFromReader(reader);
			}
		}
	}
}
